package com.alks.function.service.impl.procurement;


import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.StringUtils;
import com.alks.entity.data.entity.PcPackDetail;
import com.alks.entity.data.entity.SdMaterial;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.chengKong.assort.SdMtlTypeNewDto;
import com.alks.function.data.dto.chengKong.produce.PcLotHeadDto;
import com.alks.function.data.dto.chengKong.produce.PcLotUsageDto;
import com.alks.function.data.dto.chengKong.produce.SdStyleSizeDto;
import com.alks.function.data.dto.procurement.*;
import com.alks.function.data.request.procurement.InstructionPackageMaterialDetailsRequest;
import com.alks.function.data.request.procurement.InstructionPackageMaterialRequest;
import com.alks.function.data.request.procurement.InstructionPackageMaterialRequest2;
import com.alks.function.data.request.procurement.SdMaterialRequest;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.common.BackMapper;
import com.alks.function.mapper.procurement.BrandMaterialDefinitionMapper;
import com.alks.function.mapper.procurement.InstructionPackagingMaterialMapper;
import com.alks.function.service.procurement.InstructionPackagingMaterialService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicInteger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.alks.function.service.impl.procurement.BrandMaterialDefinitionServiceImpl.generateNewCode;


@Service
@Slf4j
public class InstructionPackagingMaterialServiceImpl implements InstructionPackagingMaterialService {

    @Autowired
    InstructionPackagingMaterialMapper instructionPackagingMaterialMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private BrandMaterialDefinitionMapper brandMaterialDefinitionMapper;

    @Autowired
    private BackMapper backMapper;

    @Autowired
    private PcLotHeadMapper pcLotHeadMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 待计算指令查询
     *
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getNotCountLotNoList(InstructionPackageMaterialRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        //正奇只要检核了就可以查到，我多加了判断，审核了才能看到
        List<InstructionPackageDto> notCountLotNoList = instructionPackagingMaterialMapper.getNotCountLotNoList(request, companyId);

        HashMap map = new HashMap<>();
        PageInfo list = new PageInfo(notCountLotNoList);
        map.put("lotNoList", notCountLotNoList);
        map.put("total", list.getTotal());
        return ResponseInfo.ok(map);
    }

    /**
     * 已处理指令查询
     *
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getProcessedLotNoList(InstructionPackageMaterialRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        List<InstructionPackageDto> notCountLotNoList = instructionPackagingMaterialMapper.getProcessedLotNoList2(request, companyId);
        //if(ObjectUtils.isNotEmpty(notCountLotNoList)){
        //    List<String> lotList = notCountLotNoList.stream().map(InstructionPackageDto::getLotNo).collect(Collectors.toList());
        //    List<InstructionPackageDto> totalCartonsList =instructionPackagingMaterialMapper.getDetailList(lotList,companyId);
        //    // 将totalCartonsList转换为Map，key为LOT_NO，value为totalCartons
        //    Map<String, Integer> totalCartonsMap = totalCartonsList.stream()
        //            .collect(Collectors.toMap(InstructionPackageDto::getLotNo, InstructionPackageDto::getTotalCartons));
        //
        //    // 直接根据Map设置totalCartons，避免循环
        //    for (InstructionPackageDto dto : notCountLotNoList) {
        //        Integer totalCartons = totalCartonsMap.get(dto.getLotNo());
        //        if (totalCartons != null) {
        //            dto.setTotalCartons(totalCartons);
        //        }
        //    }
        //}

        PageInfo list = new PageInfo(notCountLotNoList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", notCountLotNoList);
        map.put("total", list.getTotal());

        return ResponseInfo.ok(map);
    }

    /**
     * 指令包材明细：查询
     * @return
     */
    @Override
    //@AutoPageAop
    public ResponseInfo getInstructionPackageDetails(InstructionPackageMaterialRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        //复合查询
        //史倩待完善 条件有待发现
        List<InstructionPackageDetailsDto> notCountLotNoList = instructionPackagingMaterialMapper.getInstructionPackageDetails(request, companyId);

        //绿色代表材料已经采购或入库，不能更新&删除
        //1.如果在PC_SLIP_DETAIL_PACK里面代表已经入库
        //2.如果PC_PACK_DETAIL中的PUR_FLAG为Y代表已经订购
        for (InstructionPackageDetailsDto dto : notCountLotNoList) {
            if (dto.getQty() != null ) {
                dto.setStoragedFlag("Y");
            }
            if (dto.getPurNo() != null){
                dto.setPurchasedFlag("Y");
            }
        }

        PageInfo list = new PageInfo(notCountLotNoList);
        HashMap map = new HashMap<>();
        map.put("lotNoList", notCountLotNoList);
        map.put("total", list.getTotal());

        return ResponseInfo.ok(map);
    }

    /**
     * 指令包材明细：添加包材
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo addInstructionPackageDetails(InstructionPackageMaterialDetailsRequest request, String lotNo) {
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        PcPackDetail pcPackDetail = new PcPackDetail();
        BeanUtils.copyProperties(request, pcPackDetail);

        pcPackDetail.setLotNo(lotNo);
        pcPackDetail.setCompanyId(companyId);
        pcPackDetail.setShipmentId("OMJ");
        pcPackDetail.setShipmentName(request.getShipment());
        pcPackDetail.setStyle(request.getStyle());
        pcPackDetail.setSysUser(userName);
        pcPackDetail.setTtlUsage(null);
        pcPackDetail.setMtlNo(null);

        int count = instructionPackagingMaterialMapper.addInstructionPackageDetails(pcPackDetail);
        if (count > 0) {
            return ResponseInfo.ok("添加包材成功！");
        } else {
            throw new ServiceErrorException("添加包材失败！");
        }
    }

    /**
     * 指令包材明细：批量添加包材
     * @param list
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo addBatchInstructionPackageDetails(List<InstructionPackageMaterialDetailsRequest> list, String lotNo) {
        if(ObjectUtils.isEmpty(list)){
            return ResponseInfo.warn("数据为空！");
        }

        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        List<PcPackDetail> requestList = new ArrayList<>();
        for (InstructionPackageMaterialDetailsRequest request : list) {
            PcPackDetail pcPackDetail = new PcPackDetail();
            //基础数据
            pcPackDetail.setLotNo(lotNo);
            pcPackDetail.setCompanyId(companyId);
            pcPackDetail.setShipmentId("OMJ");
            pcPackDetail.setShipmentName(request.getShipment());
            pcPackDetail.setStyle(request.getStyle());
            pcPackDetail.setSysUser(userName);

            //材料数据
            //pcPackDetail.setMtlNo(request.getMtlNo());
            pcPackDetail.setSeqNo(request.getSeqNo());
            pcPackDetail.setTypeName(request.getTypeName());
            pcPackDetail.setMtlName(request.getMtlName());
            pcPackDetail.setMtlColor(request.getMtlColor());
            pcPackDetail.setMtlSpec(request.getMtlSpec());
            pcPackDetail.setMtlUnit(request.getMtlUnit());

            //要为空的数据
            //要为空的数据直接不填写就好了
//            pcPackDetail.setTtlUsage(null);

            //保存的数据
            requestList.add(pcPackDetail);
        }

        int count = instructionPackagingMaterialMapper.addInstructionPackage(requestList);
        if (count > 0) {
            return ResponseInfo.ok("添加包材明细成功！");
        } else {
            throw new ServiceErrorException("添加包材明细失败！");
        }
    }

    /**
     * 指令包材明细：编辑
     *
     * @param request
     * @return
     */
    @Override
    public ResponseInfo updateInstructionPackageDetails(InstructionPackageMaterialDetailsRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();

        PcPackDetail pcPackDetail = new PcPackDetail();
        //材料数据
        pcPackDetail.setMtlNo(request.getMtlNo());
        pcPackDetail.setMtlName(request.getMtlName());
        pcPackDetail.setMtlColor(request.getMtlColor());
        pcPackDetail.setMtlSpec(request.getMtlSpec());
        pcPackDetail.setMtlUnit(request.getMtlUnit());

        //其他数据
        pcPackDetail.setId(request.getId());
        pcPackDetail.setSeqNo(request.getSeqNo());
        pcPackDetail.setTypeName(request.getTypeName());
        pcPackDetail.setSize1(request.getSize1());
        pcPackDetail.setSize2(request.getSize2());
        pcPackDetail.setTtlUsage(request.getTtlUsage());

        //其他数据
        pcPackDetail.setCompanyId(companyId);
        pcPackDetail.setSysUser(userName);

        int count = instructionPackagingMaterialMapper.updateInstructionPackageDetails(pcPackDetail);
        if (count > 0) {
            return ResponseInfo.ok();
        } else {
            throw new ServiceErrorException("自动更新材明细失败，请联系IT人员");
        }
    }

    /**
     * 指令包材明细： 批量编辑
     * @param list
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo updateBatchInstructionPackageDetails(List<InstructionPackageMaterialDetailsRequest> list) {
        if(ObjectUtils.isEmpty(list)){
            return ResponseInfo.warn("数据为空！");
        }
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        /*判断数据-并没有对页面数据进行修改*/
        //查询

//        InstructionPackageMaterialRequest r = new InstructionPackageMaterialRequest();
//        r.setLotNo(list.get(0).getLotNo());
//        List<InstructionPackageDetailsDto> dateList = instructionPackagingMaterialMapper.getInstructionPackageDetails(r, companyId);
//        // 判断数据是否有变化
//        boolean hasChanges = false;
//        if (list.size() != dateList.size()) {
//            hasChanges = true; //有变化
//        } else {
//            for (int i = 0; i < dateList.size(); i++) {
//                if (!dateList.get(i).isEqualTo(list.get(i))) {
//                    hasChanges = true; //有变化
//                    break;
//                }
//            }
//        }
//
//        //没有变化才会提示"---"
//        if (!hasChanges) {
//            return ResponseInfo.ok("---");
//        }

        List<PcPackDetail> requestList = new ArrayList<>();
        for (InstructionPackageMaterialDetailsRequest request : list) {

            //*处理前端传的包材类别*/
            //我要对前端发给我的包材类别进行判断截断：数字+空字符串+包材类别
            // 检查typeName是否以数字开头，且后面紧跟一个空格
            String typeName = request.getTypeName();
            if (typeName != null && typeName.matches("\\d+ .*")) {
                // 截取从第一个空格之后的部分
                typeName = typeName.substring(typeName.indexOf(' ') + 1);
            }

            PcPackDetail pcPackDetail = new PcPackDetail();
            //基础数据
            pcPackDetail.setLotNo(request.getLotNo());
            pcPackDetail.setCompanyId(companyId);
            pcPackDetail.setShipmentId("OMJ");
            pcPackDetail.setShipmentName(request.getShipment());
            pcPackDetail.setStyle(request.getStyle());
            pcPackDetail.setSysUser(userName);

            //材料数据
            pcPackDetail.setSeqNo(request.getSeqNo());
            pcPackDetail.setTypeName(typeName);
            pcPackDetail.setMtlName(request.getMtlName());
            pcPackDetail.setMtlColor(request.getMtlColor());
            pcPackDetail.setMtlSpec(request.getMtlSpec());
            pcPackDetail.setMtlUnit(request.getMtlUnit());

            //其他重要的数据
            pcPackDetail.setId(request.getId());
            pcPackDetail.setMtlNo(request.getMtlNo());
            pcPackDetail.setTtlUsage(request.getTtlUsage());
            pcPackDetail.setSize1(request.getSize1());
            pcPackDetail.setSize2(request.getSize2());

            //把数据一起保存
            requestList.add(pcPackDetail);
        }

        int count = instructionPackagingMaterialMapper.updateBatchInstructionPackageDetails(requestList);
        if (count > 0) {
            return ResponseInfo.ok("包材明细更新成功！");
        } else {
            throw  new ServiceErrorException("包材明细更新失败！");
        }
    }

    /**
     * 根据指令更新鞋托数据2
     * @param lotNo
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo updateDate(String lotNo) {

        //1.先查包材明细的鞋托数据
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        List<PcPackDetail> shoesList = instructionPackagingMaterialMapper.getPackageDetailsOfShoes(lotNo, companyId);

        //2.判断数据中是否有已经下单的鞋托(vender不是null)，有的话需要先取消入库或取消订购
        // 判断是否有已下单的鞋托（vendor 不为 null）
        boolean hasOrderedShoes = shoesList.stream()
                .anyMatch(shoe -> shoe.getVendorNo() != null && !shoe.getVendorNo().trim().isEmpty());

        if (hasOrderedShoes) {
            throw new ServiceErrorException(lotNo + "指令存在已下单或已入库的鞋托材料，请先取消该指令的鞋托材料入库或订购再操作再更新鞋托！");
        }

        //3.查询指令单的鞋托数据
        List<PcLotUsageDto> usageDtoList = pcLotHeadMapper.getDetailsOfShoes(lotNo, companyId);

        // 3. 没有需要更新的数据
        if (ObjectUtils.isEmpty(usageDtoList) && ObjectUtils.isEmpty(shoesList)) {
            throw new ServiceErrorException(lotNo + "指令没有需要更新的鞋托资料！");
        }

        // 4. 指令没有鞋托，删除所有鞋托
        if (ObjectUtils.isEmpty(usageDtoList)) {
            int count = instructionPackagingMaterialMapper.deleteByXieTuo(lotNo, companyId);
            if (count > 0) {
                return ResponseInfo.ok("鞋托更新成功！");
            } else {
                throw new ServiceErrorException("鞋托更新失败！");
            }
        }

        // 5. 指令有鞋托，先删除后插入
        int deleteCount = instructionPackagingMaterialMapper.deleteByXieTuo(lotNo, companyId);

        List<PcPackDetail> requestList = new ArrayList<>();
        for (PcLotUsageDto usageDto : usageDtoList) {
            //基础数据
            PcPackDetail pcPackDetail = new PcPackDetail();
            pcPackDetail.setLotNo(lotNo);
            pcPackDetail.setCompanyId(companyId);
            pcPackDetail.setShipmentId("OMJ");
            pcPackDetail.setShipmentName(usageDto.getCustom());
            pcPackDetail.setStyle(usageDto.getStyle());
            pcPackDetail.setSysUser(userName);

            //材料数据
            pcPackDetail.setMtlNo(usageDto.getMtlNo());
            pcPackDetail.setTypeName(usageDto.getTypeName());
            pcPackDetail.setMtlName(usageDto.getMtlName());
            pcPackDetail.setMtlColor(usageDto.getMtlColor());
            pcPackDetail.setMtlSpec(usageDto.getMtlSpec());
            pcPackDetail.setMtlUnit(usageDto.getMtlUnit());
            pcPackDetail.setSize2(usageDto.getSize2());
            pcPackDetail.setSize1(usageDto.getSize1());
            pcPackDetail.setTtlUsage(usageDto.getTtlUsage());

            //包材数据
            pcPackDetail.setSeqNo(BigDecimal.valueOf(13));
            pcPackDetail.setTypeName("鞋托");

            requestList.add(pcPackDetail);
        }

        int insertCount = instructionPackagingMaterialMapper.addInstructionPackage(requestList);
        if (insertCount > 0) {
            return ResponseInfo.ok("鞋托更新成功！");
        } else {
            throw new ServiceErrorException("鞋托更新失败！");
        }
    }

    ///**
    // * 根据指令更新鞋托数据
    // * @param lotNo
    // * @return
    // */
    //@Override
    //@Transactional
    //public ResponseInfo updateDate(String lotNo) {
    //
    //    //1.先查包材明细的鞋托数据
    //    String companyId = UserIdThread.get().getCompanyId();
    //    String userName = UserIdThread.get().getUserName();
    //    List<InstructionPackageDetailsDto> shoesList = instructionPackagingMaterialMapper.getPackageDetailsOfShoes(lotNo, companyId);
    //
    //    //2.查询指令单的鞋托数据
    //   List<PcLotUsageDto> usageDtoList = pcLotHeadMapper.getDetailsOfShoes(lotNo, companyId);
    //
    //    //3.如果指令单的鞋托不在包材明细中就添加，否则就不用添加
    //    if(ObjectUtils.isEmpty(usageDtoList)){
    //        throw new ServiceErrorException("该指令的用量明细没有鞋托");
    //    }
    //
    //    // 4.将包材明细中的鞋托数据转换为集合，方便查找
    //    Set<String> existingShoesSet = shoesList.stream()
    //            .map(dto -> dto.getLotNo() + dto.getMtlNo() + dto.getMtlName() + dto.getMtlColor() + dto.getMtlSpec() + dto.getMtlUnit() + dto.getSize1() + dto.getSize2())
    //            .collect(Collectors.toSet());
    //
    //    //5.遍历添加指令单的鞋托数据
    //    List<PcPackDetail> requestList = new ArrayList<>();
    //    for (PcLotUsageDto usageDto : usageDtoList) {
    //        String uniqueKey = usageDto.getLotNo() + usageDto.getMtlNo() + usageDto.getMtlName() + usageDto.getMtlColor() + usageDto.getMtlSpec() + usageDto.getMtlUnit() + usageDto.getSize1() + usageDto.getSize2();
    //
    //        if (!existingShoesSet.contains(uniqueKey)) {
    //            // 创建新的包材明细条目
    //            PcPackDetail pcPackDetail = new PcPackDetail();
    //            //基础数据
    //            pcPackDetail.setLotNo(lotNo);
    //            pcPackDetail.setCompanyId(companyId);
    //            pcPackDetail.setShipmentId("OMJ");
    //            pcPackDetail.setShipmentName(usageDto.getCustom());
    //            pcPackDetail.setStyle(usageDto.getStyle());
    //            pcPackDetail.setSysUser(userName);
    //
    //            //材料数据
    //            pcPackDetail.setMtlNo(usageDto.getMtlNo());
    //            pcPackDetail.setTypeName(usageDto.getTypeName());
    //            pcPackDetail.setMtlName(usageDto.getMtlName());
    //            pcPackDetail.setMtlColor(usageDto.getMtlColor());
    //            pcPackDetail.setMtlSpec(usageDto.getMtlSpec());
    //            pcPackDetail.setMtlUnit(usageDto.getMtlUnit());
    //            pcPackDetail.setSize2(usageDto.getSize2());
    //            pcPackDetail.setSize1(usageDto.getSize1());
    //            pcPackDetail.setTtlUsage(usageDto.getTtlUsage());
    //
    //            //包材数据
    //            pcPackDetail.setSeqNo(BigDecimal.valueOf(13));
    //            pcPackDetail.setTypeName("鞋托");
    //
    //            //保存的数据
    //            requestList.add(pcPackDetail);
    //        }
    //    }
    //
    //    // 插入新的包材明细条目
    //    int count = 0 ;
    //    if (!requestList.isEmpty()) {
    //        count = instructionPackagingMaterialMapper.addInstructionPackage(requestList);
    //    }else{
    //        throw new ServiceErrorException("鞋托已更新过");
    //    }
    //
    //    if (count > 0) {
    //        return ResponseInfo.ok("更新鞋托成功！");
    //    } else {
    //        throw new ServiceErrorException("更新鞋托失败！");
    //    }
    //}
    ///**
    // * 根据指令更新鞋托数据2
    // * @param lotNo
    // * @return
    // */
    //@Override
    //@Transactional
    //public ResponseInfo updateDate(String lotNo) {
    //
    //    //1.先查包材明细的鞋托数据（已经入库或者下单的）
    //    String companyId = UserIdThread.get().getCompanyId();
    //    String userName = UserIdThread.get().getUserName();
    //    List<InstructionPackageDetailsDto> shoesList = instructionPackagingMaterialMapper.getPackageDetailsOfShoes2(lotNo, companyId);
    //
    //    //2.查询指令单的鞋托数据
    //    List<PcLotUsageDto> usageDtoList = pcLotHeadMapper.getDetailsOfShoes(lotNo, companyId);
    //
    //    /*判断是否有不存在指令单的材料删除的情况*/
    //    //3.如果存在包材有的材料，但是指令单没有的材料，此时包材里面的这个已经下单或者入库，提示先删除改指令已经下单或入库的鞋托材料
    //    //只有usageDtoList和shoesList都不为0的情况
    //    if(ObjectUtils.isNotEmpty(shoesList) && ObjectUtils.isNotEmpty(usageDtoList)) {
    //        // 3.1. 将指令单的鞋托数据转换为集合，用于判断是否存在
    //        Set<String> usageShoesSet = usageDtoList.stream()
    //                .map(dto ->
    //                        dto.getLotNo() + dto.getMtlNo() +  dto.getMtlName() + dto.getMtlColor() + dto.getMtlSpec() + dto.getMtlUnit() + dto.getSize1() + dto.getSize2()
    //                )
    //                .collect(Collectors.toSet());
    //
    //        // 3.2. 用于记录冲突的材料
    //        List<InstructionPackageDetailsDto> mismatchList = new ArrayList<>();
    //
    //        // 3.3. 遍历包材明细中的每个鞋托材料，判断是否在指令单中存在
    //        for (InstructionPackageDetailsDto shoe : shoesList) {
    //            String uniqueKey =
    //                    shoe.getLotNo() + shoe.getMtlNo() +  shoe.getMtlName() + shoe.getMtlColor() + shoe.getMtlSpec() + shoe.getMtlUnit() + shoe.getSize1() + shoe.getSize2();
    //
    //            if (!usageShoesSet.contains(uniqueKey)) {
    //                mismatchList.add(shoe); // 记录冲突材料
    //            }
    //        }
    //
    //        // 3.4. 如果存在冲突材料，抛出异常并提示具体材料信息
    //        if (!mismatchList.isEmpty()) {
    //            StringBuilder sb = new StringBuilder();
    //            sb.append(lotNo +"存在指令单没有的鞋托材料已下单或入库的情况，请先处理以下材料后再操作！\n");
    //
    //            for (InstructionPackageDetailsDto dto : mismatchList) {
    //                sb.append("材料：").append(dto.getMtlNo())
    //                        .append("/").append(dto.getMtlName())
    //                        .append("/").append(dto.getMtlColor())
    //                        .append("/").append(dto.getMtlSpec())
    //                        .append("/").append(dto.getMtlUnit())
    //                        .append("/").append(dto.getSize1()).append("-").append(dto.getSize2())
    //                        .append("；")
    //                        .append("\n");
    //            }
    //
    //            throw new ServiceErrorException(sb.toString());
    //        }
    //    }
    //
    //
    //    //4.先查包材明细的鞋托数据
    //    List<PcPackDetail> shoesList2 = instructionPackagingMaterialMapper.getPackageDetailsOfShoes(lotNo, companyId);
    //
    //    /*处理当前包材的数据*/
    //    //5.如果包材没有鞋托数据，指令没有鞋托数据，提示“该指令无鞋托数据”
    //    //6. 如果包材没有鞋托数据，指令有鞋托数据，把指令鞋托全部新增进去
    //    //7.如果包材有鞋托数据，指令没有鞋托数据，把包材的鞋托数据全部删除
    //
    //    //8.如果包材和指令都有鞋托数据得情况
    //    //》8.1 如果包材shoesList2中有但是指令单usageDtoList没有的数据，直接在包材中删掉这个数据
    //    //》8.2 如果包材中没有，但是指令单有，直接在包材中添加这个数据
    //    //》8.3 如果两个有相同的数据，那么把shoesList2的数据更新为usageDtoList的数据中的用量
    //
    //    if(ObjectUtils.isEmpty(usageDtoList) && ObjectUtils.isEmpty(shoesList2)) {
    //        //5.如果包材没有鞋托数据，指令没有鞋托数据，提示“该指令无鞋托数据”
    //        throw new ServiceErrorException(lotNo +"指令无鞋托数据");
    //    }else if(ObjectUtils.isNotEmpty(usageDtoList) && ObjectUtils.isEmpty(shoesList2)) {
    //        //6. 如果包材没有鞋托数据，指令有鞋托数据，把指令鞋托全部新增进去
    //        List<PcPackDetail> addAllList = new ArrayList<>();
    //        for (PcLotUsageDto usageDto : usageDtoList) {
    //            // 创建新的包材明细条目
    //              PcPackDetail pcPackDetail = new PcPackDetail();
    //              //基础数据
    //              pcPackDetail.setLotNo(lotNo);
    //              pcPackDetail.setCompanyId(companyId);
    //              pcPackDetail.setShipmentId("OMJ");
    //              pcPackDetail.setShipmentName(usageDto.getCustom());
    //              pcPackDetail.setStyle(usageDto.getStyle());
    //              pcPackDetail.setSysUser(userName);
    //
    //              //材料数据
    //              pcPackDetail.setMtlNo(usageDto.getMtlNo());
    //              pcPackDetail.setTypeName(usageDto.getTypeName());
    //              pcPackDetail.setMtlName(usageDto.getMtlName());
    //              pcPackDetail.setMtlColor(usageDto.getMtlColor());
    //              pcPackDetail.setMtlSpec(usageDto.getMtlSpec());
    //              pcPackDetail.setMtlUnit(usageDto.getMtlUnit());
    //              pcPackDetail.setSize2(usageDto.getSize2());
    //              pcPackDetail.setSize1(usageDto.getSize1());
    //              pcPackDetail.setTtlUsage(usageDto.getTtlUsage());
    //
    //              //包材数据
    //              pcPackDetail.setSeqNo(BigDecimal.valueOf(13));
    //              pcPackDetail.setTypeName("鞋托");
    //
    //              //保存的数据
    //            addAllList.add(pcPackDetail);
    //        }
    //        int count1 = 0;
    //        if (!addAllList.isEmpty()) {
    //            count1 = instructionPackagingMaterialMapper.addInstructionPackage(addAllList);
    //        }
    //        if (count1 > 0) {
    //            return ResponseInfo.ok("更新鞋托成功！");
    //        } else {
    //            throw new ServiceErrorException("更新鞋托失败！");
    //        }
    //
    //    }else if(ObjectUtils.isEmpty(usageDtoList) && ObjectUtils.isNotEmpty(shoesList2)) {
    //        //7.如果包材有鞋托数据，指令没有鞋托数据，把包材的鞋托数据全部删除
    //        int count2 = 0;
    //        count2 = instructionPackagingMaterialMapper.deleteInstructionPackage(shoesList2);
    //
    //        if (count2 > 0) {
    //            return ResponseInfo.ok("更新鞋托成功！");
    //        } else {
    //            throw new ServiceErrorException("更新鞋托失败！");
    //        }
    //    }else{
    //        //8.如果包材和指令都有鞋托数据得情况
    //        //》8.1 如果包材shoesList2中有但是指令单usageDtoList没有的数据，直接在包材中删掉这个数据
    //        //》8.2 如果包材中没有，但是指令单有，直接在包材中添加这个数据
    //        //》8.3 如果两个有相同的数据，那么把shoesList2的数据更新为usageDtoList的数据中的用量
    //        // 创建两个 Set 保存 key，用于对比
    //        Set<String> usageKeySet = new HashSet<>();
    //        Set<String> packageKeySet = new HashSet<>();
    //
    //        // 存储需要更新或删除的数据
    //        Map<String, PcPackDetail> packageMap = new HashMap<>();
    //
    //        // 遍历包材数据，构建 key -> dto 映射
    //        for (PcPackDetail dto : shoesList2) {
    //            String key = dto.getLotNo() + dto.getMtlNo() + dto.getMtlName() + dto.getMtlColor() + dto.getMtlSpec() + dto.getMtlUnit() + dto.getSize1() + dto.getSize2();
    //            packageKeySet.add(key);
    //            packageMap.put(key, dto);
    //        }
    //
    //        // 遍历指令单数据，处理新增和更新
    //        List<PcPackDetail> addList = new ArrayList<>();
    //        List<PcPackDetail> deleteList = new ArrayList<>();
    //        List<PcPackDetail> updatetList = new ArrayList<>();
    //        for (PcLotUsageDto usageDto : usageDtoList) {
    //            String key = usageDto.getLotNo() + usageDto.getMtlNo() + usageDto.getMtlName() + usageDto.getMtlColor() +
    //                    usageDto.getMtlSpec() + usageDto.getMtlUnit() + usageDto.getSize1() + usageDto.getSize2();
    //            usageKeySet.add(key);
    //
    //            if (!packageKeySet.contains(key)) {
    //                // 8.2 如果包材中没有，但是指令单有，新增
    //                PcPackDetail pcPackDetail = new PcPackDetail();
    //
    //                // 基础数据
    //                pcPackDetail.setLotNo(usageDto.getLotNo());
    //                pcPackDetail.setCompanyId(companyId);
    //                pcPackDetail.setShipmentId("OMJ");
    //                pcPackDetail.setShipmentName(usageDto.getCustom());
    //                pcPackDetail.setStyle(usageDto.getStyle());
    //                pcPackDetail.setSysUser(userName);
    //
    //                // 材料数据
    //                pcPackDetail.setMtlNo(usageDto.getMtlNo());
    //                pcPackDetail.setTypeName("鞋托"); // 固定为鞋托
    //                pcPackDetail.setMtlName(usageDto.getMtlName());
    //                pcPackDetail.setMtlColor(usageDto.getMtlColor());
    //                pcPackDetail.setMtlSpec(usageDto.getMtlSpec());
    //                pcPackDetail.setMtlUnit(usageDto.getMtlUnit());
    //                pcPackDetail.setSize2(usageDto.getSize2());
    //                pcPackDetail.setSize1(usageDto.getSize1());
    //                pcPackDetail.setTtlUsage(usageDto.getTtlUsage());
    //
    //                // 包材字段
    //                pcPackDetail.setSeqNo(BigDecimal.valueOf(13)); // 固定顺序号
    //
    //                addList.add(pcPackDetail);
    //            } else {
    //                // 8.3 如果两个有相同的数据，更新包材的用量
    //                PcPackDetail existingDto = packageMap.get(key);
    //                PcPackDetail pcPackDetail = new PcPackDetail();
    //                BeanUtils.copyProperties(pcPackDetail, existingDto);
    //                pcPackDetail.setCompanyId(companyId);
    //                pcPackDetail.setTtlUsage(usageDto.getTtlUsage()); // 更新用量
    //                updatetList.add(pcPackDetail);
    //            }
    //        }
    //
    //        // 8.1 如果包材中有但指令单没有，删除这些数据
    //        for (String key : packageKeySet) {
    //            if (!usageKeySet.contains(key)) {
    //                PcPackDetail pcPackDetail = packageMap.get(key);
    //                pcPackDetail.setCompanyId(companyId);
    //                deleteList.add(pcPackDetail);
    //            }
    //        }
    //
    //        boolean a =false;
    //        boolean b =false;
    //        boolean c =false;
    //        int count1 = 0;
    //        int count2 = 0;
    //        int count3 = 0;
    //        // 最后，批量插入新增的数据
    //        if (!addList.isEmpty()) {
    //            // 新增
    //            count1 = instructionPackagingMaterialMapper.addInstructionPackage(addList);
    //            if(count1 > 0){
    //                a = true;
    //            }
    //        }
    //
    //        if (!updatetList.isEmpty()) {
    //            // 更新用量
    //            count2 = instructionPackagingMaterialMapper.updateInstructionPackage(updatetList);
    //            if(count2 > 0){
    //                b = true;
    //            }
    //        }
    //
    //        if (!deleteList.isEmpty()) {
    //            // 根据材料删除数据
    //            count3 = instructionPackagingMaterialMapper.deleteInstructionPackage(deleteList);
    //            if(count3 > 0){
    //                c = true;
    //            }
    //        }
    //
    //        //如果有新增或删除或修改数据的时候，且他们对应的操作都成功了，就返回成功；如果没有新增、删除、修改数据的时候，返回没有数据更新；如果有新增或删除或修改数据，但是操作失败了，返回失败
    //        // 判断是否有任何操作成功
    //        if (a || b || c) {
    //            // 至少有一个操作成功
    //            return ResponseInfo.ok("更新鞋托成功！");
    //        } else if (addList.isEmpty() && updatetList.isEmpty() && deleteList.isEmpty()) {
    //            // 没有任何操作
    //            throw new ServiceErrorException("没有需要更新的鞋托资料！");
    //        } else {
    //            // 所有操作都失败
    //            throw new ServiceErrorException("更新鞋托失败！");
    //        }
    //    }
    //
    //}


    /**
     * 材料替换
     * @param request
     * @return
     */
    @Override
    public ResponseInfo updateClickDetails(InstructionPackageMaterialRequest2 request) {

        //当前指令明细
        InstructionPackageMaterialDetailsRequest detail = request.getDetail();
        //要添加的材料
        SdMaterialRequest materialData = request.getMaterialData();

        /*判断*/
        //如果材料已经订购或者入库，不能选择
        if (detail.getStoragedFlag()!= null && detail.getStoragedFlag().equals("Y")){
            return ResponseInfo.warn("该包材已入库，不能选择！");
        }
        if (detail.getPurchasedFlag() != null && detail.getPurchasedFlag().equals("Y")){
            return ResponseInfo.warn("该包材已采购，不能选择！");
        }

        PcPackDetail pcPackDetail = new PcPackDetail();
        //替换的材料数据
        pcPackDetail.setMtlNo(materialData.getMtlNo());
        pcPackDetail.setMtlColor(materialData.getMtlColor());
        pcPackDetail.setMtlName(materialData.getMtlName());
        pcPackDetail.setMtlSpec(materialData.getMtlSpec());
        pcPackDetail.setMtlUnit(materialData.getMtlUnit());

        //更改人和公司
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        pcPackDetail.setCompanyId(companyId);
        pcPackDetail.setSysUser(userName);

        //其他重要的数据
        pcPackDetail.setId(detail.getId());
        pcPackDetail.setSeqNo(detail.getSeqNo());
        pcPackDetail.setTypeName(detail.getTypeName());
        pcPackDetail.setTtlUsage(detail.getTtlUsage());
        pcPackDetail.setSize1(detail.getSize1());
        pcPackDetail.setSize2(detail.getSize2());

        //要添加的材料
        int count = instructionPackagingMaterialMapper.updateInstructionPackageDetails(pcPackDetail);
        if (count > 0) {
            return ResponseInfo.ok("材料替换成功！");
        } else {
            throw new ServiceErrorException("材料替换失败！");
        }
    }

    /**
     * 删除包材用量（整单）
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo deleteAllInstructionPackage(String lotNo) {
        String companyId = UserIdThread.get().getCompanyId();

        /*判断*/
        //绿色代表材料已经采购或入库，不能更新&删除
        InstructionPackageMaterialRequest request = new InstructionPackageMaterialRequest();
        request.setLotNo(lotNo);
        List<InstructionPackageDetailsDto> lotNoPackDetails = instructionPackagingMaterialMapper.getInstructionPackageDetails(request, companyId);
        // 2. 提取【用量不为空】的记录，才需要进行“是否已入库/已订购”的限制校验
        List<InstructionPackageDetailsDto> recordsWithQty = lotNoPackDetails.stream()
                .filter(item -> item.getTtlUsage() != null && item.getTtlUsage().compareTo(BigDecimal.ZERO) > 0)
                .collect(Collectors.toList());

        // 检查是否存在【用量不为空 + 已入库】的记录
        boolean a = recordsWithQty.stream()
                .anyMatch(item -> item.getQty() != null && item.getQty().compareTo(BigDecimal.ZERO) > 0);

        // 检查是否存在【用量不为空 + 已订购】的记录
        boolean b = recordsWithQty.stream()
                .anyMatch(item -> item.getPurNo() != null);

        if (a || b) {
            throw new ServiceErrorException("存在已订购或已入库材料，不能删除，请检查！");
        }
        ////1.如果在PC_SLIP_DETAIL_PACK里面代表已经入库
        ////2.如果PC_PACK_DETAIL中的PUR_FLAG为Y代表已经订购
        //if(ObjectUtils.isEmpty(notCountLotNoList)){
        //    throw new ServiceErrorException("没有找到指令包材类别数据");
        //}
        //InstructionPackageDetailsDto dto = notCountLotNoList.get(0);
        //if (dto.getQty() != null ) {
        //    throw new ServiceErrorException("该指令已经入库，不能删除！");
        //}
        //if (dto.getPurNo() != null){
        //    throw new ServiceErrorException("该指令开始订购，不能删除！");
        //}

        PcPackDetail pcPackDetail = new PcPackDetail();
        pcPackDetail.setLotNo(lotNo);
        pcPackDetail.setCompanyId(companyId);
        int count = instructionPackagingMaterialMapper.deleteAllInstructionPackage(pcPackDetail);
        if (count > 0) {
            return ResponseInfo.ok("删除包材用量（整单）成功！");
        } else {
            throw new ServiceErrorException("删除包材用量（整单）失败！");
        }
    }

    /**
     * 删除打勾材料
     *
     * @param request
     * @return
     * @Transactional
     */
    @Override
    @Transactional
    public ResponseInfo deleteInstructionPackageDetails(List<InstructionPackageMaterialDetailsRequest> request) {
        //史倩待完成 已经订购材料不能删除
        if (ObjectUtils.isNotEmpty(request)) {
            // 2. 提取【用量不为空】的记录，才需要进行“是否已入库/已订购”的限制校验
            List<InstructionPackageMaterialDetailsRequest> recordsWithQty = request.stream()
                    .filter(item -> item.getTtlUsage() != null && item.getTtlUsage().compareTo(BigDecimal.ZERO) > 0)
                    .collect(Collectors.toList());

            // 检查是否存在【用量不为空 + 已入库】的记录
            boolean a = recordsWithQty.stream()
                    .anyMatch(item -> "Y".equals(item.getStoragedFlag()));

            // 检查是否存在【用量不为空 + 已订购】的记录
            boolean b = recordsWithQty.stream()
                    .anyMatch(item -> "Y".equals(item.getPackedFlag()));

            if (a || b) {
                throw new ServiceErrorException("存在已订购或已入库材料，不能删除，请检查！");
            }

            ////判断：用量不为空且已经订购和入库的材料，不能删除
            //boolean a = request.stream().anyMatch(item -> item.getStoragedFlag() != null && item.getStoragedFlag().equals("Y"));
            //boolean b = request.stream().anyMatch(item -> item.getPackedFlag() != null && item.getPackedFlag().equals("Y"));
            //if (a) {
            //    throw new ServiceErrorException("已入库材料不能删除，请检查！");
            //}
            //if (b) {
            //    throw new ServiceErrorException("已订购材料不能删除，请检查！");
            //}

            String companyId = UserIdThread.get().getCompanyId();
            String userName = UserIdThread.get().getUserName();
            List<PcPackDetail> details = new ArrayList<>();
            for (InstructionPackageMaterialDetailsRequest detailsRequest : request) {
                PcPackDetail pcPackDetail = new PcPackDetail();
                BeanUtils.copyProperties(detailsRequest, pcPackDetail);
                pcPackDetail.setCompanyId(companyId);
                pcPackDetail.setSysUser(userName);
                details.add(pcPackDetail);
            }
            int count = instructionPackagingMaterialMapper.deleteInstructionPackageDetails(details);
            if (count > 0) {
                return ResponseInfo.ok("该材料明细删除成功！");
            } else {
                throw new ServiceErrorException("该材料明细删除失败！");
            }
        } else {
            throw new ServiceErrorException("请选择数据！");
        }
    }

    /**
     * 生成物料编码
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo makeMaterialCode(InstructionPackageMaterialDetailsRequest request) {
        /*1.判断*/
        if (StringUtils.isBlank(request.getMtlType()) ||  StringUtils.isBlank(request.getMtlName()) || StringUtils.isBlank(request.getMtlUnit())) {
            throw new ServiceErrorException("数据不完整！分类、材料名称和单位!");
        }
        //物料编码已存在
        if(!StringUtils.isBlank(request.getMtlNo())){
            throw new ServiceErrorException("页面上的存在物料编码，请检查！");
        }

        //上锁
        String companyId = UserIdThread.get().getCompanyId();
        String lockKey = "makeSdMaterial:" + companyId;
        String lockValue = UUID.randomUUID().toString();
        Boolean isLocked = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 5, TimeUnit.SECONDS);
        if (!isLocked) {
            throw new ServiceErrorException("系统处理数据中,请稍后重试!");
        }
        try {
            
        /*2.编码*/
        //如果根据改物料（颜色,材料，名称，规格）查询到一样的就说明该材料已经存在了，不会再生成新的；
        SdMaterial sdMaterial= new SdMaterial();
        sdMaterial.setCompanyId(companyId);
        sdMaterial.setMtlType(request.getMtlType() != "" ? request.getMtlType() : null);
        sdMaterial.setMtlName(request.getMtlName() != "" ? request.getMtlName() : null);
        sdMaterial.setMtlSpec(request.getMtlSpec() != "" ? request.getMtlSpec() : null);
        sdMaterial.setMtlUnit(request.getMtlUnit() != "" ? request.getMtlUnit() : null);
        sdMaterial.setMtlColor(request.getMtlColor() != "" ? request.getMtlColor() : null);
        SdMaterialDto sdMaterialDto = brandMaterialDefinitionMapper.getMaterialData(sdMaterial);
        //材料存在，直接取该物料编码；否则创建
        if(sdMaterialDto != null){
            sdMaterial.setMtlNo(sdMaterialDto.getMtlNo());
        }else{
            //不存在就新增
            // 1. 从数据库中获取当前最大编号
            SdMaterialDto materialData = brandMaterialDefinitionMapper.getMaterialMaxData(companyId, request.getMtlType());
            String newCode = generateNewCode(request.getMtlType(), 5, (materialData != null && materialData.getMtlNo() != null ? materialData.getMtlNo() : null));
            sdMaterial.setMtlNo(newCode);
            sdMaterial.setSysUser(UserIdThread.get().getUserName());
            int count = brandMaterialDefinitionMapper.addSdMaterial(sdMaterial);
            if (count == 0) {
                throw new ServiceErrorException("新增编码失败!");
            }
        }

        //2》》PC_PACK_DETAIL
        PcPackDetail pcPackDetail = new PcPackDetail();
        BeanUtils.copyProperties(request, pcPackDetail);
        pcPackDetail.setCompanyId(companyId);
        pcPackDetail.setMtlNo(sdMaterial.getMtlNo());
        int count2 = instructionPackagingMaterialMapper.updateInstructionPackageDetails(pcPackDetail);
        if (count2 > 0) {
            return ResponseInfo.ok("操作成功");
        } else {
            throw new ServiceErrorException("操作失败");
        }

        } finally {
            // 检查并释放锁
            String existingValue = (String) redisTemplate.opsForValue().get(lockKey);
            if (lockValue.equals(existingValue)) {
                redisTemplate.delete(lockKey); // 释放锁
            }
        }
    }

    /**
     * 指令包材明细：置空物料编码
     * @param request
     * @return
     */
    @Override
    public ResponseInfo makeMaterialCodeBeNull(InstructionPackageMaterialDetailsRequest request) {
        if(ObjectUtils.isEmpty(request.getMtlNo())){
            throw new ServiceErrorException("物料编码不存在，不能置空！");
        }
        //如果已经变绿色就不能置空
        if(request.getStoragedFlag() != null && request.getStoragedFlag().equals("Y")){
            throw new ServiceErrorException("已入库，不能置空！");
        }
        if(request.getPurchasedFlag() != null &&  request.getPurchasedFlag().equals("Y") ){
            throw new ServiceErrorException("已采购，不能置空！");
        }

        String companyId = UserIdThread.get().getCompanyId();
        PcPackDetail pcPackDetail = new PcPackDetail();
        BeanUtils.copyProperties(request,pcPackDetail);
        pcPackDetail.setCompanyId(companyId);
        pcPackDetail.setMtlNo(null);
        int count = instructionPackagingMaterialMapper.updateInstructionPackageDetails(pcPackDetail);
        if(count > 0){
            return ResponseInfo.ok("置空物料编码成功！");
        }else{
            throw new ServiceErrorException("置空物料编码失败！");
        }
    }

    /**
     * 复制到勾选指令
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo copyInstructionPackageDetails(InstructionPackageMaterialRequest2 request) {
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        //目前正在复制的材料数据
        List<InstructionPackageMaterialDetailsRequest> detailList = request.getDetailList();
        //需要被复制材料的指令集合
        List<InstructionPackageMaterialRequest> lotNoList = request.getLotNoList();
        if(ObjectUtils.isEmpty(detailList) || ObjectUtils.isEmpty(lotNoList)){
            throw new ServiceErrorException("请选择记录！");
        }

        List<PcPackDetail> list = new ArrayList<>();
        for (InstructionPackageMaterialRequest lotRequest : lotNoList) {
            for (InstructionPackageMaterialDetailsRequest materialRequest : detailList) {

                PcPackDetail pcPackDetail = new PcPackDetail();
                //基础数据
                pcPackDetail.setLotNo(lotRequest.getLotNo());
                pcPackDetail.setCompanyId(companyId);
                pcPackDetail.setShipmentId("OMJ");
                pcPackDetail.setShipmentName(lotRequest.getShipment());
                pcPackDetail.setStyle(lotRequest.getStyle());
                pcPackDetail.setSysUser(userName);

                //材料数据
                pcPackDetail.setSeqNo(materialRequest.getSeqNo());
                pcPackDetail.setTypeName(materialRequest.getTypeName());
                pcPackDetail.setMtlNo(materialRequest.getMtlNo());
                pcPackDetail.setMtlName(materialRequest.getMtlName());
                pcPackDetail.setMtlColor(materialRequest.getMtlColor());
                pcPackDetail.setMtlSpec(materialRequest.getMtlSpec());
                pcPackDetail.setMtlUnit(materialRequest.getMtlUnit());

                //其他重要的数据
//                pcPackDetail.setTtlUsage(materialRequest.getTtlUsage());
                pcPackDetail.setSize1(materialRequest.getSize1());
                pcPackDetail.setSize2(materialRequest.getSize2());

                //把数据一起保存
                list.add(pcPackDetail);
            }
        }

        int count = 0 ;
        if(list.size() > 0) {
            //总箱数也会有变化
        count = instructionPackagingMaterialMapper.addInstructionPackage(list);
        }
        if(count > 0){
            return ResponseInfo.ok("复制成功！");
        }else{
            throw new ServiceErrorException("复制失败！");
        }
    }

    /**
     * 打勾计算用量
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo calculatedConsumption(List<InstructionPackageMaterialRequest> request) {
        /*判断*/
        if(ObjectUtils.isEmpty(request)){
            throw new ServiceErrorException("请选择要计算用量的指令！");
        }
        if(request.size() > 20){
            throw new ServiceErrorException("一次最多勾选20条！");
        }
        //指令品牌为空或品牌未定义包材，不能计算！
        boolean flag = Optional.ofNullable(request)
                .map(req -> req.stream()
                 .anyMatch(r -> r.getPackedFlag() != null && "Y".equals(r.getPackedFlag())))
                .orElse(false);
        if (!flag) {
            throw new ServiceErrorException("指令品牌为空或品牌未定义包材，不能计算！");
        }

        /*赋值*/
        String companyId = UserIdThread.get().getCompanyId();
        String userName = UserIdThread.get().getUserName();
        //1.该指令的品牌-在品牌包材里面查数据
        Set<String> styleList = request.stream().map(InstructionPackageMaterialRequest::getShipment).collect(Collectors.toSet());
//        List<PcPackStyleTypeMtlDto> pcPackStyleTypeMtlDtoList = brandMaterialDefinitionMapper.getMaterialListBYStyle(styleList,companyId);
        //查询所有指令信息
        List<String> lotNoList = request.stream().map(InstructionPackageMaterialRequest::getLotNo).collect(Collectors.toList());
        List<PcLotHeadDto> styleDetails = pcLotHeadMapper.getBatchStyleDetails(lotNoList,companyId);

        List<PcPackDetail> list = new ArrayList<>();
        //把指令分开，按照指令来
        for (InstructionPackageMaterialRequest materialRequest : request) {
            //当前指令匹配到的指令信息
            List<PcLotHeadDto> headCollect = styleDetails.stream().filter(lotHeadDto -> lotHeadDto.getLotNo().equals(materialRequest.getLotNo())).collect(Collectors.toList());
            PcLotHeadDto lotHeadDto = headCollect.get(0);
            // 在品牌包材中查找与 lotHeadDto的custom 匹配的对象
            List<PcPackStyleTypeMtlDto> pcPackStyleTypeMtlDtoList = brandMaterialDefinitionMapper.getAllMaterialList(lotHeadDto.getCustom(),companyId);
            for (PcPackStyleTypeMtlDto mtlDto : pcPackStyleTypeMtlDtoList) {
//                if (mtlDto.getStyle().equals(materialRequest.getShipment())) {
                    PcPackDetail pcPackDetail = new PcPackDetail();
                    BeanUtils.copyProperties(mtlDto,pcPackDetail);
                    pcPackDetail.setCompanyId(companyId);
                    pcPackDetail.setLotNo(materialRequest.getLotNo());
//                    pcPackDetail.setShipmentName(materialRequest.getShipment());
                   //暂时不知道
                    pcPackDetail.setShipmentId("OMJ");
                    pcPackDetail.setShipmentName(materialRequest.getShipment());
                    pcPackDetail.setStyle(materialRequest.getStyle());
                //3.计算：用量的值为订单数*品牌包材的用量比
                    if(mtlDto.getMtlNo() == null){
                        pcPackDetail.setTtlUsage(mtlDto.getUsage() == null ? null : mtlDto.getUsage().multiply(lotHeadDto.getOrderQty()));
                    }else{
                        pcPackDetail.setTtlUsage(mtlDto.getUsage() == null ? BigDecimal.ZERO : mtlDto.getUsage().multiply(lotHeadDto.getOrderQty()));
                    }
                    pcPackDetail.setSysUser(userName);
                    list.add(pcPackDetail);
//                }
            }
        }
        if (ObjectUtils.isEmpty(list)) {
            throw new ServiceErrorException("打勾计算用量失败！");
        }
        int count = instructionPackagingMaterialMapper.addInstructionPackage(list);
        if(count > 0){
            return ResponseInfo.ok("打勾计算用量成功！");
        }else{
            throw new ServiceErrorException("打勾计算用量失败！");
        }
    }

    /**
     * 根据形体查size
     * @return
     */
    @Override
    public ResponseInfo getSizeListByStyle(String style) {
        String companyId = UserIdThread.get().getCompanyId();
        List<SdStyleSizeDto> sizeList = pcLotHeadMapper.getStyleShoeLastDetails(style, companyId);
        List<String> list = sizeList.stream()
                .map(SdStyleSizeDto::getSizeNo)
//                .sorted() // 这里进行了排序操作，默认是自然排序
                .collect(Collectors.toList());
//        list.add(null);
        return ResponseInfo.ok(list);
    }

}


